<template>
  <div class="template-market">
    <!-- 开源版本提示 -->
    <div class="opensource-notice" v-if="isOpenSourceVersion">
      <el-alert title="模板功能暂未开放" type="info" description="模板广场功能在开源版本中暂不可用，请关注后续版本更新。您仍可以使用软件选择和基础环境配置功能。" show-icon
        :closable="false" />
    </div>

    <!-- 页面头部 -->
    <div class="market-header" v-if="!isOpenSourceVersion">
      <div class="header-content">
        <h1 class="page-title">模板广场</h1>
        <p class="page-description">发现和使用社区分享的优质开发环境模板</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="goToCreateTemplate">
          <el-icon>
            <Plus />
          </el-icon>
          创建模板
        </el-button>
      </div>
    </div>

    <div class="market-content" v-if="!isOpenSourceVersion">
      <!-- 侧边栏导航 -->
      <div class="sidebar">
        <div class="left-nav-menu">
          <div class="nav-item" :class="{ active: activeTab === 'all' }" @click="switchTab('all')">
            <el-icon>
              <Grid />
            </el-icon>
            <span>全部模板</span>
            <span class="count" v-if="allTemplatesCount > 0">({{ allTemplatesCount }})</span>
          </div>
          <div class="nav-item" :class="{ active: activeTab === 'featured' }" @click="switchTab('featured')">
            <el-icon>
              <Star />
            </el-icon>
            <span>精选模板</span>
            <span class="count" v-if="featuredTemplatesCount > 0">({{ featuredTemplatesCount }})</span>
          </div>
        </div>
      </div>

      <!-- 主内容区域 -->
      <div class="main-content">
        <!-- 搜索和筛选 -->
        <div class="search-filters">
          <div class="search-bar">
            <el-input v-model="searchQuery" placeholder="搜索模板名称、描述或标签..." @input="handleSearchDebounced" clearable>
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </div>

          <div class="filters">
            <el-select v-model="selectedCategory" placeholder="选择分类" @change="handleCategoryChange" clearable>
              <el-option label="全部分类" value="" />
              <el-option v-for="category in categories" :key="category.code" :label="category.name"
                :value="category.code" />
            </el-select>

            <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
              <el-option label="最新发布" value="created_at" />
              <el-option label="最多下载" value="download_count" />
              <el-option label="最高评分" value="rating" />
              <el-option label="最多使用" value="use_count" />
            </el-select>
          </div>
        </div>

        <!-- 模板内容区域 -->
        <div class="templates-content">
          <!-- 内容标题 -->
          <div class="content-header">
            <h2 class="content-title">
              {{ activeTab === 'featured' ? '精选模板' : '全部模板' }}
              <span class="count">({{ totalCount }})</span>
            </h2>
          </div>

          <!-- 加载状态 -->
          <div v-loading="loading" class="templates-grid">
            <template-card v-for="template in displayTemplates" :key="template.id" :template="template"
              :show-featured-badge="false" @use="handleUseTemplate" @favorite="handleFavoriteTemplate"
              @rate="handleRateTemplate" @preview="handlePreviewTemplate" />
          </div>

          <!-- 空状态 -->
          <div v-if="!loading && displayTemplates.length === 0" class="empty-state">
            <el-empty :description="getEmptyDescription()" :image-size="80">
              <el-button type="primary" @click="goToCreateTemplate" v-if="activeTab === 'all'">
                创建第一个模板
              </el-button>
            </el-empty>
          </div>

          <!-- 分页 -->
          <div v-if="totalCount > pageSize" class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalCount"
              :page-sizes="[12, 24, 48]" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handlePageChange" />
          </div>
        </div>
      </div>
    </div>

    <!-- 模板预览对话框 -->
    <el-dialog v-model="showPreviewDialog" title="模板预览" width="800px">
      <div v-if="previewingTemplate" class="template-preview">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模板名称">
            {{ previewingTemplate.name }}
          </el-descriptions-item>
          <el-descriptions-item label="创建者">
            {{ previewingTemplate.createdBy }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(previewingTemplate.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="使用次数">
            {{ previewingTemplate.downloadCount || 0 }} 次
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ previewingTemplate.description }}
          </el-descriptions-item>
        </el-descriptions>

        <h4 style="margin: 20px 0 12px 0;">包含的软件</h4>
        <el-table :data="previewingTemplate.softwareList" style="width: 100%">
          <el-table-column label="软件名称">
            <template #default="scope">
              {{ scope.row.displayName || scope.row.name || '未知软件' }}
            </template>
          </el-table-column>
          <el-table-column label="版本" width="120">
            <template #default="scope">
              {{ scope.row.version || 'latest' }}
            </template>
          </el-table-column>
          <el-table-column label="分类" width="100">
            <template #default="scope">
              <el-tag size="small" :type="getCategoryType(scope.row.category)">
                {{ scope.row.category || '其他' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPreviewDialog = false">关闭</el-button>
          <el-button type="primary" @click="handleUseTemplate(previewingTemplate)">
            使用此模板
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import TemplateCard from '@/components/TemplateCard.vue'
import { TEMPLATE_CATEGORIES, getCategoryType } from '@/constants/templateCategories'
import { useSoftwareStore } from '@/stores/software'
import { useTemplateStore } from '@/stores/template'
import { useUserStore } from '@/stores/user'
import { Grid, Plus, Search, Star } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const softwareStore = useSoftwareStore()
const templateStore = useTemplateStore()

// 检测是否为开源版本
const isOpenSourceVersion = ref(true) // 开源版本默认为true

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const selectedCategory = ref('')
const sortBy = ref('created_at')
const currentPage = ref(1)
const pageSize = ref(12)
const totalCount = ref(0)

// 标签页切换
const activeTab = ref('all') // 'all' 或 'featured'

// 模板数据
const allTemplates = ref([])
const featuredTemplates = ref([])

// 预览相关
const showPreviewDialog = ref(false)
const previewingTemplate = ref(null)

// 分类数据
const categories = ref(TEMPLATE_CATEGORIES)

// 计算属性
const displayTemplates = computed(() =>
{
  return activeTab.value === 'featured' ? featuredTemplates.value : allTemplates.value
})

const allTemplatesCount = computed(() =>
{
  return allTemplates.value.length
})

const featuredTemplatesCount = computed(() =>
{
  return featuredTemplates.value.length
})

// 搜索参数
const searchParams = computed(() => ({
  query: searchQuery.value,
  category: selectedCategory.value,
  sortBy: sortBy.value,
  featured: activeTab.value === 'featured',
  page: currentPage.value,
  size: pageSize.value
}))

// 方法
const switchTab = (tab) =>
{
  if (activeTab.value === tab) return

  activeTab.value = tab
  currentPage.value = 1

  // 不要清空搜索和筛选条件，保持用户的输入
  // searchQuery.value = ''
  // selectedCategory.value = ''

  if (tab === 'featured')
  {
    loadFeaturedTemplates()
  } else
  {
    loadAllTemplates()
  }
}

const loadAllTemplates = async () =>
{
  try
  {
    loading.value = true
    const params = new URLSearchParams()

    // 基础参数
    params.append('isPublic', 'true') // 只显示公开模板

    // 搜索和筛选参数
    if (searchQuery.value && searchQuery.value.trim()) params.append('query', searchQuery.value.trim())
    if (selectedCategory.value) params.append('category', selectedCategory.value)
    if (sortBy.value) params.append('sortBy', sortBy.value)

    // 分页参数
    params.append('page', currentPage.value - 1) // 后端从0开始
    params.append('size', pageSize.value)

    // 构建请求头，如果用户已登录则添加认证头
    const headers = {
      'Content-Type': 'application/json'
    }
    if (userStore.isLoggedIn && userStore.token)
    {
      headers['Authorization'] = `Bearer ${userStore.token}`
    }

    console.log('加载全部模板，请求参数:', params.toString())

    const response = await fetch(`/api/templates?${params}`, {
      headers
    })
    const result = await response.json()

    console.log('全部模板API响应:', result)

    if (result.code === 200)
    {
      allTemplates.value = result.data || []
      totalCount.value = result.data?.length || 0

      // 同步模板状态到store
      templateStore.batchSetTemplateStates(allTemplates.value)
      templateStore.batchSyncTemplateStates(allTemplates.value)
    } else
    {
      throw new Error(result.message || '加载模板失败')
    }
  } catch (error)
  {
    console.error('加载全部模板失败:', error)
    ElMessage.error('加载模板失败: ' + error.message)
  } finally
  {
    loading.value = false
  }
}

const loadFeaturedTemplates = async () =>
{
  try
  {
    loading.value = true
    const params = new URLSearchParams()

    // 使用全部模板API，通过featured参数过滤精选模板
    params.append('isPublic', 'true') // 只显示公开模板
    params.append('featured', 'true') // 只显示精选模板

    // 分页参数
    params.append('page', currentPage.value - 1) // 后端从0开始
    params.append('size', pageSize.value)

    // 搜索和筛选参数
    if (searchQuery.value && searchQuery.value.trim()) params.append('query', searchQuery.value.trim())
    if (selectedCategory.value) params.append('category', selectedCategory.value)
    if (sortBy.value) params.append('sortBy', sortBy.value)

    // 构建请求头，如果用户已登录则添加认证头
    const headers = {
      'Content-Type': 'application/json'
    }
    if (userStore.isLoggedIn && userStore.token)
    {
      headers['Authorization'] = `Bearer ${userStore.token}`
    }

    console.log('加载精选模板，请求参数:', params.toString())
    console.log('精选模板搜索词:', searchQuery.value)
    console.log('精选模板分类:', selectedCategory.value)

    // 使用全部模板API而不是专门的精选模板API
    const response = await fetch(`/api/templates?${params}`, {
      headers
    })
    const result = await response.json()

    console.log('精选模板API响应:', result)

    if (result.code === 200)
    {
      featuredTemplates.value = result.data || []
      totalCount.value = result.data?.length || 0

      // 同步精选模板状态到store
      templateStore.batchSetTemplateStates(featuredTemplates.value)
      templateStore.batchSyncTemplateStates(featuredTemplates.value)
    } else
    {
      throw new Error(result.message || '加载精选模板失败')
    }
  } catch (error)
  {
    console.error('加载精选模板失败:', error)
    ElMessage.error('加载精选模板失败: ' + error.message)
  } finally
  {
    loading.value = false
  }
}

const loadInitialData = async () =>
{
  // 先加载全部模板的总数（用于侧边栏显示）
  try
  {
    const headers = {
      'Content-Type': 'application/json'
    }
    if (userStore.isLoggedIn && userStore.token)
    {
      headers['Authorization'] = `Bearer ${userStore.token}`
    }

    // 加载全部模板数量
    const allResponse = await fetch('/api/templates?isPublic=true&size=1', { headers })
    const allResult = await allResponse.json()
    if (allResult.code === 200)
    {
      // 这里获取实际的总数，可能需要调整API来返回总数
    }

    // 加载精选模板数量
    const featuredResponse = await fetch('/api/templates?featured=true&isPublic=true&size=1', { headers })
    const featuredResult = await featuredResponse.json()
    if (featuredResult.code === 200)
    {
      // 这里获取精选模板的总数
    }

    // 根据当前标签加载对应数据
    if (activeTab.value === 'featured')
    {
      await loadFeaturedTemplates()
    } else
    {
      await loadAllTemplates()
    }
  } catch (error)
  {
    console.error('加载初始数据失败:', error)
  }
}

const handleSearch = () =>
{
  currentPage.value = 1
  if (activeTab.value === 'featured')
  {
    loadFeaturedTemplates()
  } else
  {
    loadAllTemplates()
  }
}

// 防抖搜索
let searchTimeout = null
const handleSearchDebounced = () =>
{
  if (searchTimeout)
  {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() =>
  {
    handleSearch()
  }, 300) // 300ms 防抖
}

const handleCategoryChange = () =>
{
  currentPage.value = 1
  if (activeTab.value === 'featured')
  {
    loadFeaturedTemplates()
  } else
  {
    loadAllTemplates()
  }
}

const handleSortChange = () =>
{
  currentPage.value = 1
  if (activeTab.value === 'featured')
  {
    loadFeaturedTemplates()
  } else
  {
    loadAllTemplates()
  }
}

const handlePageChange = () =>
{
  if (activeTab.value === 'featured')
  {
    loadFeaturedTemplates()
  } else
  {
    loadAllTemplates()
  }
}

const handleSizeChange = () =>
{
  currentPage.value = 1
  if (activeTab.value === 'featured')
  {
    loadFeaturedTemplates()
  } else
  {
    loadAllTemplates()
  }
}

const getEmptyDescription = () =>
{
  if (searchQuery.value || selectedCategory.value)
  {
    return '没有找到符合条件的模板'
  }
  return activeTab.value === 'featured' ? '暂无精选模板' : '暂无模板'
}

const handleUseTemplate = async (template) =>
{
  try
  {
    if (!userStore.isLoggedIn)
    {
      ElMessage.warning('请先登录')
      return
    }

    const confirmed = await ElMessageBox.confirm(
      `确定要使用模板"${template.name}"吗？这将导入模板中的软件配置。`,
      '使用模板',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    if (confirmed)
    {
      // 调用后端API记录使用次数
      const useResponse = await fetch(`/api/templates/${template.id}/use`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(userStore.token && { 'Authorization': `Bearer ${userStore.token}` })
        }
      })

      const useResult = await useResponse.json()

      if (useResult.code === 200)
      {
        // 清空当前选择
        softwareStore.clearSelectedSoftware()

        // 添加模板中的软件
        if (template.softwareList && template.softwareList.length > 0)
        {
          template.softwareList.forEach(software =>
          {
            softwareStore.addSoftware({
              id: software.id,
              name: software.name,
              displayName: software.displayName,
              latestVersion: { version: software.version }
            })
          })
        }

        // 更新本地模板的使用次数显示
        template.downloadCount = (template.downloadCount || 0) + 1

        ElMessage.success(`已应用模板：${template.name}`)
        router.push('/software')
      } else
      {
        throw new Error(useResult.message || '记录使用失败')
      }
    }
  } catch (error)
  {
    // 用户取消操作
  }
}

const handleFavoriteTemplate = async (template) =>
{
  try
  {
    if (!userStore.isLoggedIn)
    {
      ElMessage.warning('请先登录')
      return
    }

    const response = await fetch(`/api/template-enhancements/${template.id}/favorite`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    const result = await response.json()
    if (result.code === 200)
    {
      // 使用后端返回的状态和消息
      const { isFavorited, message } = result.data
      ElMessage.success(message)

      // 更新全局状态
      templateStore.setFavoriteState(template.id, isFavorited)

      // 同步所有相同模板的状态
      allTemplates.value.forEach(t =>
      {
        if (t.id === template.id)
        {
          t.isFavorited = isFavorited
        }
      })
      featuredTemplates.value.forEach(t =>
      {
        if (t.id === template.id)
        {
          t.isFavorited = isFavorited
        }
      })
    } else
    {
      throw new Error(result.message || '操作失败')
    }
  } catch (error)
  {
    ElMessage.error('操作失败: ' + error.message)
  }
}

const goToCreateTemplate = () =>
{
  if (!userStore.isLoggedIn)
  {
    ElMessage.warning('请先登录')
    return
  }

  // 设置标记，让我的模板页面自动打开创建弹窗
  sessionStorage.setItem('autoOpenCreateDialog', 'true')

  // 跳转到我的模板页面
  router.push('/templates')
}

const handleRateTemplate = async (template, rating) =>
{
  try
  {
    if (!userStore.isLoggedIn)
    {
      ElMessage.warning('请先登录')
      return
    }

    const response = await fetch(`/api/template-enhancements/${template.id}/rating`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${userStore.token}`
      },
      body: JSON.stringify({ rating })
    })

    const result = await response.json()
    if (result.code === 200)
    {
      const { averageRating, ratingCount, message } = result.data
      ElMessage.success(message)

      // 更新全局状态
      templateStore.setRatingState(template.id, averageRating, ratingCount)

      // 同步所有相同模板的评分
      allTemplates.value.forEach(t =>
      {
        if (t.id === template.id)
        {
          t.rating = averageRating
          t.ratingCount = ratingCount
        }
      })
      featuredTemplates.value.forEach(t =>
      {
        if (t.id === template.id)
        {
          t.rating = averageRating
          t.ratingCount = ratingCount
        }
      })
    } else
    {
      throw new Error(result.message || '评分失败')
    }
  } catch (error)
  {
    ElMessage.error('评分失败: ' + error.message)
  }
}

const handlePreviewTemplate = (template) =>
{
  previewingTemplate.value = template
  showPreviewDialog.value = true
}

// 工具函数
const formatDate = (dateString) =>
{
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 生命周期
onMounted(() =>
{
  // 如果是开源版本，不加载模板数据
  if (!isOpenSourceVersion.value)
  {
    loadInitialData()
  }
})
</script>

<style scoped>
.template-market {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 开源版本提示样式 */
.opensource-notice {
  margin-bottom: 32px;
}

.opensource-notice :deep(.el-alert) {
  border-radius: 12px;
  padding: 20px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 1px solid #0ea5e9;
}

.opensource-notice :deep(.el-alert__title) {
  font-size: 18px;
  font-weight: 600;
  color: #0c4a6e;
}

.opensource-notice :deep(.el-alert__description) {
  font-size: 14px;
  color: #0c4a6e;
  line-height: 1.6;
  margin-top: 8px;
}

.market-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e4e7ed;
}

.header-content .page-title {
  font-size: 32px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.header-content .page-description {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.market-content {
  display: flex;
  gap: 24px;
}

/* 侧边栏样式 */
.sidebar {
  flex-shrink: 0;
  width: 240px;
}

.left-nav-menu {
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  cursor: pointer;
  transition: all 0.3s;
  border-bottom: 1px solid #f5f7fa;
  font-size: 16px;
  color: #606266;
  flex: 1;
  justify-content: flex-start;
}

.nav-item:last-child {
  border-bottom: none;
}

.nav-item:hover {
  background: #f5f7fa;
  color: #409eff;
}

.nav-item.active {
  background: #409eff;
  color: #fff;
}

.nav-item .count {
  font-size: 14px;
  color: #909399;
  margin-left: auto;
}

.nav-item.active .count {
  color: rgba(255, 255, 255, 0.8);
}

.nav-item .el-icon {
  font-size: 18px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  min-width: 0;
}

.search-filters {
  margin-bottom: 32px;
}

.search-bar {
  margin-bottom: 16px;
}

.search-bar .el-input {
  max-width: 400px;
}

.filters {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.templates-content {
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  padding: 24px;
}

.content-header {
  margin-bottom: 24px;
}

.content-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.content-title .count {
  font-size: 16px;
  font-weight: 400;
  color: #909399;
}

.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
  min-height: 200px;
}

.empty-state {
  text-align: center;
  padding: 64px 0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .market-content {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
  }

  .left-nav-menu {
    display: flex;
    overflow-x: auto;
  }

  .nav-item {
    flex-shrink: 0;
    white-space: nowrap;
    border-bottom: none;
    border-right: 1px solid #f5f7fa;
  }

  .nav-item:last-child {
    border-right: none;
  }
}

@media (max-width: 768px) {
  .template-market {
    padding: 16px;
  }

  .market-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .filters {
    flex-direction: column;
    align-items: stretch;
  }

  .templates-grid {
    grid-template-columns: 1fr;
  }

  .nav-item {
    font-size: 14px;
    padding: 12px 16px;
  }

  .nav-item .count {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .templates-content {
    padding: 16px;
  }

  .content-title {
    font-size: 20px;
  }

  .left-nav-menu {
    gap: 0;
  }

  .nav-item {
    padding: 10px 12px;
  }
}
</style>
